package utils

import (
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtSecret = []byte("lvdao_rustdesk_api_server")

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

type Claims struct {
	UserId   int    `json:"id"`
	ClientId string `json:"client_id"`
	jwt.StandardClaims
}

func GenerateToken(userId int, username string, clientId string, uuid string) (string, error) {
	nowTime := time.Now().Unix() - 1000
	expireTime := time.Now().Add(time.Hour * 24 * 365).Unix()

	claims := Claims{
		UserId:   userId,
		ClientId: clientId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime,
			NotBefore: nowTime,
			Issuer:    "chris",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	t, err := token.SignedString(jwtSecret)
	return t, err
}

func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			return nil, TokenMalformed
		} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
			return nil, TokenExpired
		} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
			return nil, TokenNotValidYet
		} else {
			return nil, TokenInvalid
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*Claims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid
	} else {
		return nil, TokenInvalid
	}
}
